package com;

import java.io.IOException;

import java.net.Socket;
import java.util.Scanner;

public class MainClient {
	public static MainClient main = null;
	private MainClientThread client = null;
	private ThreadPool threadPool = new ThreadPool();

	public static void main(String[] args) {
		main = new MainClient();
		main.Run(args);
	}

	private void Run(String[] args) {
		int port = 0;
		String address = "";
		
		try {
			port = Integer.parseInt(getParam(args, "-p"));
			if (port < 0) throw new Exception();
		} catch (Exception e) {
			System.out.println("Input Port Error");
			return;
		}
		try {
			address = getParam(args, "-h");
			if (address.length() < 0) throw new Exception();
		} catch (Exception e) {
			System.out.println("Input Address Port Error");
			return;
		}
		
		try {
			client = new MainClientThread(new Socket(address, port), threadPool);
			client.newThreadStrat();
		} catch (IOException e1) {
			System.out.println(e1.getMessage() + "__Not Open Client, Address: " + address +", Port:" + port);
			return;
		}

		Scanner in = new Scanner(System.in);
		while (in.hasNext()) {
			if (in.next().equals("exit")) {
				break;
			}
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				System.out.println(e.getMessage());
			}
		}
		threadPool.closeThreadPool();
	}



	private String getParam(String[] args, String key) {
		for (int i = 0; i < args.length; i++) {
			if (args[i].equals(key)) {
				return args[i + 1].trim();
			}
		}
		return "";
	}
}
